package com.leetcode.partition2;

/**
 * @author `RKC`
 * @date 2021/8/23 18:15
 */
public class LC123买卖股票的最佳时机3 {

    public static int maxProfit(int[] prices) {
        return dynamicProgramming(prices);
    }

    public static void main(String[] args) {
        int[] prices = {3, 3, 5, 0, 0, 3, 1, 4};
        System.out.println(maxProfit(prices));
    }

    /**
     * 每天都有5个状态
     * 0：没有操作
     * 1：第一次买入或已经买入：i天买入股票dp[i][1]=dp[i-1][0]-prices[i]；第i-1天就已经持有股票dp[i][1]=dp[i-1][1]
     * 2：第一次卖出或已经卖出：i天卖出dp[i][2]=dp[i-1][1]+prices[i]；i-1天就已经卖出dp[i][2]=dp[i-1][2]
     * 3：第二次买入或已经买入：i天买入dp[i][3]=dp[i-1][2]-prices[i]；i-1天就已经买入dp[i][3]=dp[i-1][3]
     * 4：第二次卖出或已经卖出：i天卖出dp[i][4]=dp[i-1][3]+prices[i]；i-1天就已经卖出dp[i][4]=dp[i-1][4]
     */
    private static int dynamicProgramming(int[] prices) {
        int[][] dp = new int[prices.length][5];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        dp[0][2] = 0;
        dp[0][3] = -prices[0];
        dp[0][4] = 0;
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = dp[i - 1][0];
            dp[i][1] = Math.max(dp[i - 1][0] - prices[i], dp[i - 1][1]);
            dp[i][2] = Math.max(dp[i - 1][1] + prices[i], dp[i - 1][2]);
            dp[i][3] = Math.max(dp[i - 1][2] - prices[i], dp[i - 1][3]);
            dp[i][4] = Math.max(dp[i - 1][3] + prices[i], dp[i - 1][4]);
        }
        return dp[prices.length - 1][4];
    }
}
